import { Hono } from "hono";
import { HTTPException } from "hono/http-exception";
import { z } from "zod";
import { Image } from "@/models/Image";
import AppDataSource from "@/common/database";
import { createWriteStream, writeFileSync } from "node:fs";
import { join } from "node:path";
import { mkdirSync } from "fs";
import { Store } from "@/models/Store";

const imageRoute = new Hono();

const querySchema = z.object({
  page: z.coerce.number().default(1),
  pageSize: z.coerce.number().default(10),
  storeId: z.coerce.number(),
});

imageRoute.get("/list", async (c) => {
  let query = c.req.query();
  let result = querySchema.safeParse(query);

  if (!result.success) {
    let message = result.error.issues
      .map((item) => item.path.join(",") + item.message)
      .join(",");
    throw new HTTPException(400, { message });
  }

  let [list, count] = await AppDataSource.createQueryBuilder()
    .select("image")
    .from(Image, "image")
    .where("image.storeId = :storeId", { storeId: result.data.storeId })
    .getManyAndCount();

  return c.json({ message: "hello", code: 200, data: { list, count } });
});
/**
 * 图片上传本地
 */
imageRoute.post("/upload", async (c) => {
  // 上传文件
  let body = await c.req.parseBody();
  if (body["file"] instanceof File) {
    console.log(`收到文件大小：${body["file"].size}`);
  }

  if (!(body["file"] instanceof File)) {
    throw new HTTPException(400, { message: "文件不能为空" });
  }

  // 创建上传目录
  const uploadDir = join(process.cwd(), "public", "uploads");
  mkdirSync(uploadDir, { recursive: true });

  // 生成时间戳文件名
  const ext = body["file"].name.split(".").pop() || "";
  const newFilename = `${Date.now()}${ext ? "." + ext : ""}`;
  const filePath = join(uploadDir, newFilename);

  // 保存文件
  const fileBuffer = Buffer.from(await body["file"].arrayBuffer());
  writeFileSync(filePath, fileBuffer);

  let store = await Store.findOne({
    where: { id: +body["storeId"] },
  });

  if (!store) {
    throw new HTTPException(400, { message: "店铺不存在" });
  }

  // 保存到数据库
  let image = await Image.save({
    name: newFilename,
    path: `/uploads/${newFilename}`,
    store,
  });

  return c.json({
    message: "上传成功",
    code: 200,
    data: { filename: newFilename, image },
  });

  //   上传文件
});

imageRoute.post("/uploadBase64", async (c) => {
  // 添加请求体验证
  const body = await c.req.parseBody();
  const { base64 } = body;

  if (typeof base64 !== "string") {
    throw new HTTPException(400, { message: "base64参数必须为字符串" });
  }

  // 添加base64格式验证
  if (!base64.startsWith("data:image/")) {
    throw new HTTPException(400, { message: "无效的base64图片格式" });
  }

  // 创建上传目录（保持原样）
  const uploadDir = join(process.cwd(), "public", "uploads");
  mkdirSync(uploadDir, { recursive: true });

  // 改进文件扩展名获取方式
  const mimeType = base64.split(";")[0].split("/")[1];
  const ext = mimeType === "jpeg" ? "jpg" : mimeType;
  const newFilename = `${Date.now()}.${ext}`;

  // 提取纯base64数据
  const base64Data = base64.split("base64,").pop();
  if (!base64Data) {
    throw new HTTPException(400, { message: "无效的base64数据" });
  }

  // 保存文件（保持原样）
  const fileBuffer = Buffer.from(base64Data, "base64");
  writeFileSync(join(uploadDir, newFilename), fileBuffer);

  return c.json({
    message: "上传成功",
    code: 200,
    data: { filename: newFilename, path: `/uploads/${newFilename}` },
  });
});

/**
 * 图片上传OSS
 */
imageRoute.post("/oss", async (c) => {
  return c.json({ message: "上传成功", code: 200 });
});

export default imageRoute;
